#include <iostream>
#include <curl/curl.h>
#include <curl/easy.h>
#include <boost/format.hpp>

#include "CosServer.h"
#include "ImgUrl.h"
#include "trace_worker.h"
#include "String.h"
#include "ClientManager.h"
#include "JsonHelper.h"
#include "ServerManager.h"

static boost::mutex g_insMutexCalc;

CCosServer* CCosServer::_instance = NULL;

CCosServer* CCosServer::instance() 
{	
	if (NULL == _instance)
	{
		boost::unique_lock<boost::mutex> guardMutex(g_insMutexCalc);
		if (NULL == _instance)
		{
			_instance = new CCosServer;
		}
	}
	return _instance;
}

CCosServer::CCosServer()
{   trace_worker();
    CServerManager::instance()->RegisterMethod("getInfoQRCode", boost::bind(&CCosServer::GetInfoQRCode, this, _1, _2));
}

CCosServer::~CCosServer()
{}

void CCosServer::GetInfoQRCode(rapidjson::Document &document, rapidjson::Value &returnValue)
{   trace_worker();
    if (!document.HasMember("openId")
        || !document.HasMember("appId")
        || !document.HasMember("content")
        || !document["content"].IsObject()
        || !document["content"].HasMember("pubInfoId"))
    {
        return ;
    }
    const std::string &appId = document["appId"].GetString();
    const std::string &pubInfoId = document["content"]["pubInfoId"].GetString();
    std::string infoQRCode;
    if (CCosDb::instance()->GetInfoQRCode(document, appId, pubInfoId, infoQRCode) == false)
    {
        return;
    }
    
    returnValue.AddMember("type", "getInfoQRCode", document.GetAllocator());
    returnValue.AddMember("openId", document["openId"], document.GetAllocator());
    returnValue.AddMember("content", rapidjson::Value(infoQRCode.c_str(), document.GetAllocator()), document.GetAllocator());
}

